//
//  CheckGatewayOnlineConfigApi.m
//  AFNetworking
//
//  Created by tracyhenry on 2022/9/20.
//
#import "BaseSendCommand.h"
#import "CheckGatewayOnlineConfigApi.h"
#import "SiterHelp.h"
#import "Single.h"
#import "SiterAPI.h"
#import "NSString+CY.h"
#import "NetworkUnit.h"
#import <AWSIoT/AWSIoTDataManager.h>
#import <AWSIoT/AWSIoTMessage.h>
#import "ToolBox.h"
#import "TimeHelper.h"
#import "DataModel.h"
#import "NVLogManager.h"

static NSString *const uploadTopic = @"$aws/things/%@/shadow/name/shadowName/update";
static NSString *const ackTopic = @"st/siterlink/ack_from_gw/%@";
static NSString *const commandTopic = @"st/siterlink/to_gw/%@";


@interface CheckGatewayOnlineConfigApi()

@end


@implementation CheckGatewayOnlineConfigApi

#pragma -mark struct
-(id)initWithDevId:(NSString *)devId withMac:(NSString *)mac withHandler:(void(^)(NSError *,id))handler {
    if(self = [super init]){
        self.devId = devId;
        self.mac = mac;
        self.handler = handler;
        [[AWSIoTDataManager IoTDataManagerForKey:[[Siter sharedInstance] getAWSIOTDATAMANAGERKEY]] subscribeToTopic:[NSString stringWithFormat:uploadTopic,self.devId] QoS:AWSIoTMQTTQoSMessageDeliveryAttemptedAtLeastOnce fullCallback:^(NSString * _Nonnull topic, AWSIoTMessage * _Nonnull message) {
            NVLogInfo(@"网关上线:%@",message.message);
            dispatch_sync(dispatch_get_main_queue(), ^{
                self.handler(nil,nil);
                [[AWSIoTDataManager IoTDataManagerForKey:[[Siter sharedInstance] getAWSIOTDATAMANAGERKEY]] unsubscribeTopic:[NSString stringWithFormat:uploadTopic,self.devId]];
                [[AWSIoTDataManager IoTDataManagerForKey:[[Siter sharedInstance] getAWSIOTDATAMANAGERKEY]] unsubscribeTopic:[NSString stringWithFormat:ackTopic,self.devId]];
            });

        }];
    }
    return self;
}


- (id)requestArgumentCommand {
    self.msgId = [Single sharedInstanced].msg_id;
    [Single sharedInstanced].msg_id++;
    if([Single sharedInstanced].msg_id==65536){
        [Single sharedInstanced].msg_id=0;
    }
    return @{
             @"namespace":@"config",
             @"source":@"app",
             @"target":@"gateway",
             @"hw_id":self.mac,
             @"msg_id":@(self.msgId),
             @"msg":@{
                 @"CMD_CODE":[self requestCmdId],
                 @"str1":@"is_online",
                 @"str2":@"",
                 @"str3":@"",
               }
            };
}


-(BOOL)responseArgumentCommandId:(int)cmdId{
    return cmdId==ANWSER_OK;
}

-(void)responseResult:(NSNumber *)cmdId withData1:(NSString *)data_str1 withData2:(NSString *)data_str2{
    if([self responseArgumentCommandId:[cmdId intValue]]){
            if([data_str1 containsString:@"OK"]){
                self.handler(nil,nil);
            }else{
                NSError *error = [[NSError alloc] initWithDomain:NSCocoaErrorDomain code:502 userInfo:nil];
                self.handler(error,nil);
            }
        [[AWSIoTDataManager IoTDataManagerForKey:[[Siter sharedInstance] getAWSIOTDATAMANAGERKEY]] unsubscribeTopic:[NSString stringWithFormat:uploadTopic,self.devId]];
        [[AWSIoTDataManager IoTDataManagerForKey:[[Siter sharedInstance] getAWSIOTDATAMANAGERKEY]] unsubscribeTopic:[NSString stringWithFormat:ackTopic,self.devId]];
    }else{
        [[AWSIoTDataManager IoTDataManagerForKey:[[Siter sharedInstance] getAWSIOTDATAMANAGERKEY]] unsubscribeTopic:[NSString stringWithFormat:uploadTopic,self.devId]];
        [[AWSIoTDataManager IoTDataManagerForKey:[[Siter sharedInstance] getAWSIOTDATAMANAGERKEY]] unsubscribeTopic:[NSString stringWithFormat:ackTopic,self.devId]];
    }
}

- (id)requestDevId{
    return self.devId;
}

- (id)requestCmdId{
    return @CheckGatewayIsOnline;
}


#pragma -mark method
-(void)startSend {
    NSDictionary *senddata = [self requestArgumentCommand];
    NVLogInfo(@"发送数据MQTT:%@", senddata);
    DebugInfo *info = [[DebugInfo alloc] init];
    [info setTime:[TimeHelper getCurrentTimes]];
    [info setIsSend:YES];
    [info setContent:[self convertToJsonData:senddata]];
    [[ToolBox sharedToolBox] addDebugLog:info];
    [[AWSIoTDataManager IoTDataManagerForKey:[[Siter sharedInstance] getAWSIOTDATAMANAGERKEY]] publishString:[self convertToJsonData:senddata] onTopic:[NSString stringWithFormat:commandTopic,self.devId] QoS:AWSIoTMQTTQoSMessageDeliveryAttemptedAtLeastOnce];
    [[AWSIoTDataManager IoTDataManagerForKey:[[Siter sharedInstance] getAWSIOTDATAMANAGERKEY]] subscribeToTopic:[NSString stringWithFormat:ackTopic,self.devId] QoS:AWSIoTMQTTQoSMessageDeliveryAttemptedAtLeastOnce fullCallback:^(NSString * _Nonnull topic, AWSIoTMessage * _Nonnull message) {
        NVLogInfo(@"MQTT应答:%@",message.message);
        dispatch_sync(dispatch_get_main_queue(), ^{
            DebugInfo *debuginfo = [[DebugInfo alloc] init];
            [debuginfo setTime:[TimeHelper getCurrentTimes]];
            [debuginfo setContent:message.message];
            [[ToolBox sharedToolBox] addDebugLog:debuginfo];
            NSData * data = [message.message dataUsingEncoding:NSUTF8StringEncoding];
            NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            if(jsonDict!=nil){
                //刷新UI的代码放到主线程执行
                DataModel *model = [[DataModel alloc] initWithDictionary:jsonDict error:nil];
                [self deviceHandler:model];
            }
        });
    }];
}


-(NSString *)convertToJsonData:(NSDictionary *)dict{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    
    if (!jsonData) {
        NVLogInfo(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    
    NSRange range = {0,jsonString.length};
    
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
    
}

#pragma -mark delegate
-(void)deviceHandler:(DataModel *)message{
    if([self.mac isEqualToString:message.hw_id]){
        NSNumber *cmd = message.msg.CMD_CODE;
        NSString *data_str1 =   message.msg.str1;
        NSString *data_str2 =   message.msg.str2;
        if([self responseArgumentCommandId:[cmd intValue]]){
          [self responseResult:cmd withData1:data_str1 withData2:data_str2];
        }
    }
}

-(void)dealloc{
    self.handler=nil;
    [[AWSIoTDataManager IoTDataManagerForKey:[[Siter sharedInstance] getAWSIOTDATAMANAGERKEY]] unsubscribeTopic:[NSString stringWithFormat:ackTopic,self.devId]];
}
@end
